package com.crcode.crm.service.Industry.impl;
import com.crcode.crm.bean.Industry.IndustryBean;
import com.crcode.crm.dao.Industry.IndustryDao;
import com.crcode.crm.service.Industry.IndustryService;
import com.crcode.crm.utils.PageVo;
import com.crcode.crm.utils.ResultPageUtil;
import com.crcode.crm.utils.ResultUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * @author lmz
 * @company Peter
 * @create 2019/3/25  11:18
 */
@Service
public class IndustryServiceImpl implements IndustryService {
    @Autowired
    private IndustryDao industryRepository;

    /**
     * 查询行业
     * @param params
     * @param vo
     * @return
     */

    @Override
    public ResultPageUtil findAllIndustry(Map<String, Object> params, PageVo vo) {
        Integer pageIndex = vo.getPageIndex() - 1;
        Pageable pageable = null;
        if (StringUtils.isNotEmpty(vo.getOrderBy())) {
            if (vo.getOrderDesc() == 1) {
                pageable = PageRequest.of(pageIndex, vo.getPageSize(), Sort.Direction.DESC, vo.getOrderBy());
            } else if (vo.getOrderDesc() == 0) {
                pageable = PageRequest.of(pageIndex, vo.getPageSize(), Sort.Direction.ASC, vo.getOrderBy());
            }
        } else {
            pageable = PageRequest.of(pageIndex, vo.getPageSize());
        }
        Page<IndustryBean> page = this.industryRepository.findAll(spec(params), pageable);
        ResultPageUtil ru = new ResultPageUtil();
        ru.setCurrentPage(vo.getPageIndex());
        ru.setPageSize(vo.getPageSize());
        ru.setTotalPages(page.getTotalPages());
        ru.setRows(page.getContent());
        ru.setTotal(page.getTotalElements());
        return ru;

    }

    private Specification<IndustryBean> spec(final Map<String, Object> param) {
        Specification<IndustryBean> spec = new Specification<IndustryBean>() {

            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<IndustryBean> root, CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                //System.out.println(param.get("ind_name"));
                //System.out.println("---------"+root.get("ind_name"));
                if (param.get("puuid") != null) {
                    predicates.add(cb.equal(root.get("puuid"), param.get("puuid")));
                }
                if (StringUtils.isNotEmpty(param.get("indName").toString())) {
                    predicates.add(cb.like(root.get("indName"), "%" + param.get("indName").toString() + "%"));

                }

                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return spec;
    }


    @Override
    public List<IndustryBean> findIndustryByuuid(String uuid) {
        return null;
    }

    /**
     * 添加行业
     *
     * @param industryBean
     * @return
     */
    @Override
    public ResultUtil addIndustry(IndustryBean industryBean) {
        ResultUtil resultUtil = new ResultUtil();
        //查询数据库中是否有此uuid的数据，没有执行添加，有执行更新
        int sum = industryRepository.findByuuid(industryBean.getUuid());
        //执行添加操作
        if (sum < 1) {

            if (StringUtils.isEmpty(industryBean.getPuuid())) {
                industryBean.setPuuid("0");

            }
            //根据当前的puuid和名称查找该模块下是否具有相同的行业名称
            int count = industryRepository.findByPuuidAndIndname(industryBean.getIndName(), industryBean.getPuuid());
            if (count > 0) {
                resultUtil.setStatus(false);
                resultUtil.setInfo("当前节点下已存在此行业名称");
                resultUtil.setObj(null);
                return resultUtil;

            } else {
                try {
                    industryRepository.save(industryBean);
                    resultUtil.setStatus(true);
                    resultUtil.setInfo("添加成功");
                    resultUtil.setObj(industryBean);
                    return resultUtil;
                } catch (Exception e) {
                    e.printStackTrace();
                    resultUtil.setStatus(false);
                    resultUtil.setInfo("程序错误·");
                    resultUtil.setObj(industryBean);
                    return resultUtil;
                }


            }

        } else {//编辑业务

            //根据当前的puuid和名称查找该模块下是否具有相同的行业名称
            int count = industryRepository.findByPuuidAndIndNameAndUuidNot(industryBean.getPuuid(), industryBean.getIndName(), industryBean.getUuid());
            if (count > 0) {
                resultUtil.setStatus(false);
                resultUtil.setInfo("当前节点下已存在行业名称");
                resultUtil.setObj(null);
                return resultUtil;

            } else {

                try {
                    industryRepository.save(industryBean);
                    resultUtil.setStatus(true);
                    resultUtil.setInfo("修改成功成功");
                    resultUtil.setObj(industryBean);
                    return resultUtil;
                } catch (Exception e) {
                    e.printStackTrace();
                    resultUtil.setStatus(false);
                    resultUtil.setInfo("修改失败");
                    resultUtil.setObj(industryBean);
                    return resultUtil;
                }
            }

        }


    }


    /**
     * 更新行业
     *
     * @param industryBean
     * @return
     */

    @Override
    public boolean updateIndustry(IndustryBean industryBean) {
        industryRepository.save(industryBean);
        return false;
    }

    /**
     * 更根据uuid删除数据，同时删除起子节点下的所有数据
     *
     * @param uuid
     * @return
     */
    @Override
    public ResultUtil deleteIndustry(String uuid) {
        ResultUtil resultUtil = new ResultUtil();
        String[] uuids = uuid.split(",");
        List<String> list = new ArrayList<>();
        //查询所有子集uuid
        for (String str : uuids) {

            //讲父级uuid添加到集合中
            list.add(str);
            list.addAll(this.searchSunUuids(str, new ArrayList<>()));
        }
//        //set集合转为list
//        List list = new ArrayList(uuidlist);
        //System.out.println(JSON.toJSONString(list));
        int sum = industryRepository.deleteIndustryBeansByUuidIn(list);
        resultUtil.setObj(list);
        resultUtil.setInfo(sum > 0 ? "成功删除数据" : "数据删除失败");
        resultUtil.setStatus(sum > 0 ? true : false);
        return resultUtil;
    }

    /**
     * 根据父程序序号查找所有子程序序号
     */
    public List<String> searchSunUuids(String uuid, List<String> rlist) {
        List<String> list = industryRepository.findByPuuid(uuid);
        System.out.println(list.size());

        if (list.size() > 0) {
            for (String sid : list) {
                //再次调用此方法，找出无限级的子集uuid
                searchSunUuids(sid, rlist);
                rlist.add(sid);
            }
        }

        return rlist;
    }

    /**
     * 组装ztree需要的数据
     *
     * @return
     */
    @Override
    public List<IndustryBean> loadztree(String uuid) {
        //Map<String,Object> alldata=new HashMap<>();
        IndustryBean industryBean = new IndustryBean();
        industryBean.setId(0);
        industryBean.setUuid("0");
        industryBean.setPuuid("-100");
        industryBean.setIndName("所有行业");
        industryBean.setIndRemark("所有行业");

        //List<Map<String, Object>> mapList = new ArrayList<>();
        List<IndustryBean> list = industryRepository.findAll();
        list.add(industryBean);
        //System.out.println(list.size());
        //System.out.println(list.size());
        /*for (IndustryBean industryBean:list){
            Map<String,Object> map=new HashMap<>();
            //判断puuid不为空的为根节点
            map.put("id",industryBean.getId());
            map.put("uuid",industryBean.getUuid());
            map.put("puuid",industryBean.getPuuid());
            map.put("name",industryBean.getInd_name());
            mapList.add(map);
        }
        alldata.put("ss",mapList);*/
        return list;
    }

    /**
     * 检查是否具有相同的行业
     *
     * @param indName
     * @return
     */
    @Override
    public int checkIndName(String indName) {

        return industryRepository.findByIndname(indName);
    }


    @Override
    public List<IndustryBean> findAllParent() {
        return industryRepository.findByPuuidAndUuidNotNull("0");
    }
}
